import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/task.dart';
import 'task_detail_page.dart';

class PendingTasksPage extends StatefulWidget {
  final List<Task> tasks;
  final Function(Task) onTaskUpdate;

  const PendingTasksPage({
    Key? key,
    required this.tasks,
    required this.onTaskUpdate,
  }) : super(key: key);

  @override
  _PendingTasksPageState createState() => _PendingTasksPageState();
}

class _PendingTasksPageState extends State<PendingTasksPage> {
  // 获取所有未完成任务
  List<Task> get _allPendingTasks {
    return widget.tasks
        .where((task) => !task.isCompleted && !task.isDeleted)
        .toList();
  }

  // 获取今天未完成任务
  List<Task> get _todayPendingTasks {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    return _allPendingTasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      return taskDate.isAtSameMomentAs(today);
    }).toList()
      ..sort((a, b) => a.time.compareTo(b.time));
  }

  // 获取未来未完成任务
  List<Task> get _futurePendingTasks {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    return _allPendingTasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      return taskDate.isAfter(today);
    }).toList()
      ..sort((a, b) => a.time.compareTo(b.time));
  }

  // 获取过去未完成任务
  List<Task> get _overduePendingTasks {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    return _allPendingTasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      return taskDate.isBefore(today);
    }).toList()
      ..sort((a, b) => b.time.compareTo(a.time)); // 按日期倒序排列，最近的在前
  }

  // 获取任务时间类型的颜色
  Color _getTaskTimeColor(Task task) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final taskDate = DateTime(task.time.year, task.time.month, task.time.day);

    if (taskDate.isAtSameMomentAs(today)) {
      return Colors.orange; // 今天 - 橙色
    } else if (taskDate.isAfter(today)) {
      return Colors.blue; // 未来 - 蓝色
    } else {
      return Colors.red; // 过去 - 红色
    }
  }

  // 完成任务
  void _completeTask(Task task) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('完成任务'),
        content: Text('确定要将任务"${task.title}"标记为已完成吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              task.isCompleted = true;
              task.completedTime = DateTime.now();
              widget.onTaskUpdate(task);
              Navigator.pop(context);
            },
            child: const Text(
              '完成',
              style: TextStyle(color: Colors.green),
            ),
          ),
        ],
      ),
    );
  }

  // 双击删除任务
  void _deleteTask(Task task) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除任务'),
        content: Text('确定要删除任务"${task.title}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              task.isDeleted = true;
              widget.onTaskUpdate(task);
              Navigator.pop(context);
            },
            child: const Text(
              '删除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  // 构建任务项
  Widget _buildTaskItem(Task task) {
    final color = _getTaskTimeColor(task);
    
    return GestureDetector(
      onTap: () => _openTaskDetail(task),
      onDoubleTap: () => _deleteTask(task),
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: color.withOpacity(0.3),
            width: 2,
          ),
          boxShadow: [
            BoxShadow(
              color: color.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            // 左侧颜色指示器
            Container(
              width: 4,
              height: 40,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(width: 16),
            // 任务内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    task.title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    DateFormat('MM月dd日 EEEE HH:mm').format(task.time),
                    style: TextStyle(
                      fontSize: 12,
                      color: color,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      _buildPriorityTag(task.priority),
                      const SizedBox(width: 8),
                      _buildCategoryTag(task.category),
                      if (task.note != null && task.note!.isNotEmpty) ...[
                        const SizedBox(width: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                            border: Border.all(
                              color: Colors.blue.withOpacity(0.3),
                              width: 1,
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.note_outlined,
                                size: 10,
                                color: Colors.blue,
                              ),
                              const SizedBox(width: 2),
                              Text(
                                '备注',
                                style: TextStyle(
                                  fontSize: 8,
                                  color: Colors.blue,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                      if (task.location.isNotEmpty && task.location != 'Home') ...[
                        const SizedBox(width: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                            border: Border.all(
                              color: Colors.grey.withOpacity(0.3),
                              width: 1,
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.location_on_outlined,
                                size: 10,
                                color: Colors.grey[600],
                              ),
                              const SizedBox(width: 2),
                              Text(
                                task.location,
                                style: TextStyle(
                                  fontSize: 8,
                                  color: Colors.grey[600],
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ),
            // 右侧状态指示器
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                _getTaskStatusText(task),
                style: TextStyle(
                  fontSize: 10,
                  color: color,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取任务状态文本
  String _getTaskStatusText(Task task) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final taskDate = DateTime(task.time.year, task.time.month, task.time.day);

    if (taskDate.isAtSameMomentAs(today)) {
      return '今日';
    } else if (taskDate.isAfter(today)) {
      final difference = taskDate.difference(today).inDays;
      if (difference == 1) {
        return '明天';
      } else if (difference <= 7) {
        return '${difference}天后';
      } else {
        return '未来';
      }
    } else {
      final difference = today.difference(taskDate).inDays;
      if (difference == 1) {
        return '昨天';
      } else {
        return '逾期${difference}天';
      }
    }
  }

  // 构建分组标题
  Widget _buildSectionHeader(String title, int count, Color color) {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            _getSectionIcon(title),
            color: color,
            size: 20,
          ),
          const SizedBox(width: 8),
          Text(
            title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const Spacer(),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              '$count',
              style: const TextStyle(
                fontSize: 12,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 获取分组图标
  IconData _getSectionIcon(String title) {
    switch (title) {
      case '今天未完成':
        return Icons.today;
      case '未来任务':
        return Icons.schedule;
      case '逾期任务':
        return Icons.warning;
      default:
        return Icons.task_alt;
    }
  }

  @override
  Widget build(BuildContext context) {
    final todayTasks = _todayPendingTasks;
    final futureTasks = _futurePendingTasks;
    final overdueTasks = _overduePendingTasks;
    final totalTasks = todayTasks.length + futureTasks.length + overdueTasks.length;

    return Scaffold(
      appBar: AppBar(
        title: const Text('未完成任务'),
        backgroundColor: Colors.transparent,
        elevation: 0,
        actions: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            margin: const EdgeInsets.only(right: 16),
            decoration: BoxDecoration(
              color: Colors.orange.withOpacity(0.1),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Text(
              '共 $totalTasks 项',
              style: TextStyle(
                color: Colors.orange[700],
                fontWeight: FontWeight.bold,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      body: totalTasks == 0
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.check_circle_outline,
                    size: 64,
                    color: Colors.green[300],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '太棒了！\n所有任务都已完成',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.green[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            )
          : ListView(
              children: [
                // 今天未完成任务
                if (todayTasks.isNotEmpty) ...[
                  _buildSectionHeader('今天未完成', todayTasks.length, Colors.orange),
                  ...todayTasks.map((task) => _buildTaskItem(task)).toList(),
                ],

                // 未来任务
                if (futureTasks.isNotEmpty) ...[
                  _buildSectionHeader('未来任务', futureTasks.length, Colors.blue),
                  ...futureTasks.map((task) => _buildTaskItem(task)).toList(),
                ],

                // 逾期任务
                if (overdueTasks.isNotEmpty) ...[
                  _buildSectionHeader('逾期任务', overdueTasks.length, Colors.red),
                  ...overdueTasks.map((task) => _buildTaskItem(task)).toList(),
                ],

                const SizedBox(height: 20),
              ],
            ),
      bottomNavigationBar: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: Row(
          children: [
            Icon(
              Icons.info_outline,
              size: 16,
              color: Colors.grey[600],
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                '点击任务完成，双击删除任务',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 打开任务详情
  void _openTaskDetail(Task task) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TaskDetailPage(
          task: task,
          onTaskUpdate: (updatedTask) {
            setState(() {
              widget.onTaskUpdate(updatedTask);
            });
          },
          onTaskDelete: (task) {
            setState(() {
              widget.onTaskUpdate(task);
            });
          },
        ),
      ),
    );
  }

  // 构建优先级标签
  Widget _buildPriorityTag(int priority) {
    Color color;
    String text;
    IconData icon;
    
    switch (priority) {
      case 1:
        color = Colors.green;
        text = '低';
        icon = Icons.keyboard_arrow_down;
        break;
      case 2:
        color = Colors.orange;
        text = '中';
        icon = Icons.remove;
        break;
      case 3:
        color = Colors.red;
        text = '高';
        icon = Icons.keyboard_arrow_up;
        break;
      default:
        color = Colors.grey;
        text = '中';
        icon = Icons.remove;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 10,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            text,
            style: TextStyle(
              fontSize: 8,
              color: color,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 构建分类标签
  Widget _buildCategoryTag(String category) {
    Color color;
    IconData icon;
    
    switch (category) {
      case 'Personal':
        color = Colors.blue;
        icon = Icons.person;
        break;
      case 'Work':
        color = Colors.purple;
        icon = Icons.work;
        break;
      case 'Private':
        color = Colors.teal;
        icon = Icons.lock;
        break;
      case 'Meeting':
        color = Colors.orange;
        icon = Icons.people;
        break;
      case 'Events':
        color = Colors.pink;
        icon = Icons.event;
        break;
      default:
        color = Colors.grey;
        icon = Icons.label;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 10,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            category,
            style: TextStyle(
              fontSize: 8,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
} 